package com.example.student.controller;

import com.example.student.common.Result;
import com.example.student.entity.SysMenu;
import com.example.student.model.MenuVO;
import com.example.student.service.MenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/menus")
public class MenuController {

    @Resource
    private MenuService menuService;

    /**
     * 获取当前用户的菜单列表
     */
    @GetMapping("/current")
    public Result<List<MenuVO>> getCurrentUserMenus() {
        return Result.success(menuService.getCurrentUserMenus());
    }

    /**
     * 获取当前用户的导航菜单
     */
    @GetMapping("/nav")
    public Result<List<MenuVO>> getUserNavMenus() {
        return Result.success(menuService.getUserNavMenus());
    }

    /**
     * 获取所有菜单列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public Result<List<MenuVO>> list() {
        return Result.success(menuService.getAllMenus());
    }

    /**
     * 获取菜单树形结构
     */
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public Result<List<MenuVO>> getMenuTree() {
        return Result.success(menuService.getMenuTree());
    }

    /**
     * 获取菜单详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public Result<SysMenu> getById(@PathVariable Long id) {
        return Result.success(menuService.getMenuById(id));
    }

    /**
     * 根据角色ID获取菜单ID列表
     */
    @GetMapping("/role/{roleId}")
    @PreAuthorize("hasAuthority('system:role:edit')")
    public Result<List<Long>> getMenuIdsByRoleId(@PathVariable Long roleId) {
        return Result.success(menuService.getMenuIdsByRoleId(roleId));
    }

    /**
     * 添加菜单
     */
    @PostMapping
    @PreAuthorize("hasAuthority('system:menu:add')")
    public Result<Void> add(@Valid @RequestBody SysMenu menu) {
        menuService.addMenu(menu);
        return Result.success();
    }

    /**
     * 更新菜单
     */
    @PutMapping
    @PreAuthorize("hasAuthority('system:menu:edit')")
    public Result<Void> update(@Valid @RequestBody SysMenu menu) {
        menuService.updateMenu(menu);
        return Result.success();
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        menuService.deleteMenu(id);
        return Result.success();
    }
} 